﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;
using System.Collections.Generic;
using System.IO;
using BUS;
using DTO;
using System.Text;
using System.Net.Configuration;
using System.Net;
using System.Net.Mail;

namespace Cucre
{
    public partial class WebForm12 : System.Web.UI.Page
    {
        public DataClasses1DataContext Data = new DataClasses1DataContext();
        string city;
        int LoaiTinKhuyenMai;
        protected override void OnPreInit(EventArgs e)
        {
            base.OnPreInit(e);
            string path = Server.MapPath("theme.txt");
            StreamReader SR = new StreamReader(path);
            string nameTheme = SR.ReadLine();
            SR.Close();
            base.OnPreInit(e);
            if (Session["MyTheme"] == null)
            {
                Session.Add("MyTheme", nameTheme);
                Page.Theme = (string)Session["MyTheme"];
            }
            else
            {
                Page.Theme = (string)Session["MyTheme"];
            }
         
        }

        protected void Page_Load(object sender, EventArgs e)
        {
           
            city = DropDownList1.SelectedValue.Trim();
            LoaiTinKhuyenMai = LoaiTinKMDropDownList.SelectedIndex;
           
            if (!IsPostBack)
            {
                GridViewDataBind();
                if (DoanhNghiep_DropDownList.Items.Count == 0)
                {
                    List<PROVIDER> listProvider = ProviderBUS.GetAllProvider();
                    for (int i = 0; i < listProvider.Count; ++i)
                        DoanhNghiep_DropDownList.Items.Add(listProvider[i].COMPANY_NAME);
                }
            }
        }
       

        protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
        {
            city = DropDownList1.SelectedValue.Trim();
            GridViewDataBind();
        }
      
        public void DangKhuyenMaiDataBind()
        {

            var query = from product in Data.PRODUCTs
                        where ((product.STATUS.Value == 1) && (product.CITY.Trim() == city.Trim()) && (product.VISIBLE == true)
                               && ((product.TIME_START.Value - DateTime.Today).TotalSeconds < 0)
                                  && ((product.TIME_STOP.Value - DateTime.Today).TotalSeconds > 0))
                              select new
                              {
                                  IDPRODUCT = product.IDPRODUCT,
                                  PROVIDER_NAME = product.PROVIDER.COMPANY_NAME,
                                  Name_Product = product.Name_Product,                                  
                                  TIME_START = product.TIME_START.Value.ToShortDateString(),
                                  TIME_STOP = product.TIME_STOP.Value.ToShortDateString(),
                                  PRICE = product.PRICE,
                                  CITY = product.CITY
                              };
            DangKhuyenMai_GridView.DataSource = query;
            DangKhuyenMai_GridView.DataBind();
        }

        public void SapKhuyenMaiDataBind()
        {
            var query = from product in Data.PRODUCTs
                             where (((product.TIME_START.Value - DateTime.Today).TotalSeconds > 0) && (product.CITY.Trim() == city.Trim())
                               && (product.STATUS.Value == 1) && (product.VISIBLE == true))
                             select new
                             {
                                 IDPRODUCT = product.IDPRODUCT,
                                 PROVIDER_NAME = product.PROVIDER.COMPANY_NAME,
                                 Name_Product = product.Name_Product,
                                 PRICE = product.PRICE,
                                 TIME_START = product.TIME_START.Value.ToShortDateString(),
                                 TIME_STOP = product.TIME_STOP.Value.ToShortDateString(),
                                 CITY = product.CITY
                             };
            DangKhuyenMai_GridView.DataSource = query;
            DangKhuyenMai_GridView.DataBind();
           
        }

        public void TinKhuyenMaiChuaDuyetDataBind()
        {
            var query = from product in Data.PRODUCTs
                                 where ((product.STATUS.Value == 0) && (string.Compare(product.CITY, city, true) == 0) && (product.VISIBLE == true))
                                 select new
                                 {
                                     IDPRODUCT = product.IDPRODUCT,
                                     PROVIDER_NAME = product.PROVIDER.COMPANY_NAME,
                                     Name_Product = product.Name_Product,
                                     PRICE = product.PRICE,
                                     TIME_START = product.TIME_START.Value.ToShortDateString(),
                                     TIME_STOP = product.TIME_STOP.Value.ToShortDateString(),
                                     CITY = product.CITY
                                 };
            DangKhuyenMai_GridView.DataSource = query;
            DangKhuyenMai_GridView.DataBind();
           
        }

        public void TinKhuyenMaiDaKetThucDataBind()
        {
            var query = from product in Data.PRODUCTs
                                 where (((product.TIME_STOP.Value - DateTime.Today).TotalSeconds < 0) &&
                                 (product.CITY.Trim() == city.Trim()) && (product.STATUS.Value == 1) && (product.VISIBLE == true))
                                 select new
                                 {
                                     IDPRODUCT = product.IDPRODUCT,
                                     PROVIDER_NAME = product.PROVIDER.COMPANY_NAME,
                                     Name_Product = product.Name_Product,
                                     PRICE = product.PRICE,
                                     TIME_START = product.TIME_START.Value.ToShortDateString(),
                                     TIME_STOP = product.TIME_STOP.Value.ToShortDateString(),
                                     CITY = product.CITY
                                 };
            DangKhuyenMai_GridView.DataSource = query;
            DangKhuyenMai_GridView.DataBind();
           
        }

        public void GridViewDataBind()
        {
            switch (LoaiTinKhuyenMai)
            {
                case 0: //dang khuyen mai
                    DangKhuyenMaiDataBind();
                    break;
                case 1:// sap khuyen mai
                    SapKhuyenMaiDataBind();
                    break;
                case 2:// khuyen mai chua duyet
                    TinKhuyenMaiChuaDuyetDataBind();
                    break;
                case 3:// da ket thuc
                    TinKhuyenMaiDaKetThucDataBind();
                    break;
            }
        }

        //---- khu vuc dang khuyen mai
        protected void DangKhuyenMai_GridView_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            try
            {
                int id = int.Parse(DangKhuyenMai_GridView.Rows[e.RowIndex].Cells[1].Text.Trim());
                ProductBUS.Delete(id);
                GridViewDataBind();
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "clientScript", "alert('Qúa Trình Thực Hiện Thành Công, Tin Khuyến Mãi Đã Được Xóa !!!!')", true);
            }
            catch
            {
                e.Cancel = true;
            }
        }
       
        protected void SelectAll_DangKM_bt_Click(object sender, EventArgs e)
        {
                  
            for (int i = 0; i < DangKhuyenMai_GridView.Rows.Count; ++i)
            {
                ((System.Web.UI.WebControls.CheckBox)DangKhuyenMai_GridView.Rows[i].FindControl("CheckDangKhuyenMai")).Checked = true;
            }
                 
        }
      
        protected void DeSelectAll_DangKM_bt_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < DangKhuyenMai_GridView.Rows.Count; ++i)
            {
                ((System.Web.UI.WebControls.CheckBox)DangKhuyenMai_GridView.Rows[i].FindControl("CheckDangKhuyenMai")).Checked = false;
            }
        }

        protected void Delete_DangKM_bt_Click(object sender, EventArgs e)
        {
            try
            {
                bool isChecked;
                int id = -1;
                for (int i = 0; i < DangKhuyenMai_GridView.Rows.Count; ++i)
                {
                    isChecked = ((System.Web.UI.WebControls.CheckBox)DangKhuyenMai_GridView.Rows[i].FindControl("CheckDangKhuyenMai")).Checked;
                    if (isChecked)
                    {
                        id = int.Parse(DangKhuyenMai_GridView.Rows[i].Cells[1].Text.Trim());
                        ProductBUS.Delete(id);
                        GridViewDataBind();
                    }
                }
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "clientScript", "alert('Qúa Trình Thực Hiện Thành Công !!!!')", true);  
            }
            catch (Exception ex)
            {
                string message= "alert('" + ex.Message + "')";
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "clientScript",message, true);  
            }
        }       

        protected void DangKhuyenMai_GridView_DataBound(object sender, EventArgs e)
        {
            if (DangKhuyenMai_GridView.Rows.Count == 0)
            {
                LabelKhuyenMai.Text = "Không Có Tin Khuyến Mãi Nào Trong Danh Sách Này";
            }
            else
            {
                LabelKhuyenMai.Text = "";
            }

        }

        protected void DangKhuyenMai_GridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            DangKhuyenMai_GridView.PageIndex = e.NewPageIndex;
            GridViewDataBind();
        }
     

        protected void DangKhuyenMai_GridView_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
        {           
            DangKhuyenMai_GridView.SelectedIndex = e.NewSelectedIndex;
            int id=int.Parse(DangKhuyenMai_GridView.Rows[e.NewSelectedIndex].Cells[1].Text);
            PRODUCT Product = ProductBUS.GetProduct(id);
            if (Product == null)
                return;
            CityDropDownList.SelectedValue = Product.CITY.Trim();
            DoanhNghiep_DropDownList.SelectedValue= Product.PROVIDER.COMPANY_NAME.Trim(); ;
            txtTenSanPham.Text = Product.Name_Product;
            tareaSloganSanPham.Value = Product.SLOGAN;
            txtGiaSanPham.Text = Product.PRICE.ToString();
            txtGiam.Text = Product.RATE_DECREASE.ToString();
            txtMaxNumber.Text = Product.MAX_NUMBER.ToString();
            txtNgayBatDau.Text = Product.TIME_START.Value.ToShortDateString();
            txtNgayKetThuc.Text = Product.TIME_STOP.Value.ToShortDateString();
            tareaDKAP.Value = Product.Conditions_Apply;
            tareaTNNB.Value = Product.Features;
            txtImagesSanPham.Text = Product.IMAGE;
            Editor1.Text = Product.CONTENT;
        }

        protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
        {
            LoaiTinKhuyenMai = LoaiTinKMDropDownList.SelectedIndex;
            GridViewDataBind();
        }

        protected void btSave1_Click(object sender, EventArgs e)
        {
            try
            {
                PRODUCT newProduct = new PRODUCT();
                newProduct.CITY = CityDropDownList.SelectedValue.Trim();
                newProduct.Name_Product = txtTenSanPham.Text;
                newProduct.IDPROVIDER = ProviderBUS.GetIDProvider(DoanhNghiep_DropDownList.SelectedValue.Trim());
                newProduct.SLOGAN = tareaSloganSanPham.Value;
                newProduct.PRICE = double.Parse(txtGiaSanPham.Text.Trim());
                newProduct.RATE_DECREASE = int.Parse(txtGiam.Text.Trim());
                newProduct.MAX_NUMBER = int.Parse(txtMaxNumber.Text.Trim());
                newProduct.TIME_START = DateTime.Parse(txtNgayBatDau.Text.Trim());
                newProduct.TIME_STOP = DateTime.Parse(txtNgayKetThuc.Text.Trim());
                newProduct.STATUS = 1;
                newProduct.Conditions_Apply = tareaDKAP.Value;
                newProduct.Features = tareaTNNB.Value;
                if (txtImagesSanPham.Text.Trim() != "")
                    newProduct.IMAGE = txtImagesSanPham.Text.Trim();
                else
                    newProduct.IMAGE = @"images\Products\product1\";
                  newProduct.CONTENT= Editor1.Text;
                bool result=ProductBUS.Insert(newProduct);
                if (result)
                {
                    ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "clientScript", "alert('Qúa Trình Thực Hiện Thành Công !!!!')", true);
                    GridViewDataBind();
                }
                else
                {
                    ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "clientScript", "alert('Qúa Trình Thực Hiện Thất bại .vui lòng kiểm tra lại !!!!')", true);
                }
            }
            catch (Exception ex)
            {
                string message = "alert(' Error : " + ex.Message + "')";
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "clientScript", message, true);
            }
        }

        protected void btUpdate_Click(object sender, EventArgs e)
        {
            if (DangKhuyenMai_GridView.SelectedIndex < 0)
                return;
            try
            {
                int id = int.Parse(DangKhuyenMai_GridView.Rows[DangKhuyenMai_GridView.SelectedIndex].Cells[1].Text);
                PRODUCT Product = ProductBUS.GetProduct(id);
                Product.CITY = CityDropDownList.SelectedValue.Trim();
                Product.Name_Product = txtTenSanPham.Text;
                Product.SLOGAN = tareaSloganSanPham.Value;
                Product.PRICE = double.Parse(txtGiaSanPham.Text.Trim());
                Product.RATE_DECREASE = int.Parse(txtGiam.Text.Trim());
                Product.MAX_NUMBER = int.Parse(txtMaxNumber.Text.Trim());
                Product.TIME_START = DateTime.Parse(txtNgayBatDau.Text.Trim());
                Product.TIME_STOP = DateTime.Parse(txtNgayKetThuc.Text.Trim());
                Product.Conditions_Apply = tareaDKAP.Value;
                Product.Features = tareaTNNB.Value;
                if (txtImagesSanPham.Text.Trim() != "")
                    Product.IMAGE = txtImagesSanPham.Text.Trim();
                else
                    Product.IMAGE =@"images\Products\product1\";
                  Product.CONTENT = Editor1.Text;
                  bool result = ProductBUS.Update(Product);
                if (result)
                {
                    ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "clientScript", "alert('Qúa Trình Thực Hiện Thành Công !!!!')", true);
                    GridViewDataBind();
                }
                else
                {
                    ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "clientScript", "alert('Qúa Trình Thực Hiện Thất bại .vui lòng kiểm tra lại !!!!')", true);
                }
             }
            catch (Exception ex)
            {
                string message = "alert('" + ex.Message + "')";
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "clientScript", message, true);
            }

        }

        protected void btDelete_Click(object sender, EventArgs e)
        {

            if (DangKhuyenMai_GridView.SelectedIndex < 0)
                return;
            try
            {
                int id = int.Parse(DangKhuyenMai_GridView.Rows[DangKhuyenMai_GridView.SelectedIndex].Cells[1].Text);
                bool result=ProductBUS.Delete(id);
                if (result)
                {
                    ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "clientScript", "alert('Qúa Trình Thực Hiện Thành Công !!!!')", true);
                    GridViewDataBind();
                }
                else
                    ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "clientScript", "alert('Qúa Trình Thực Hiện Thất Bại !!!!')", true);
            }
            catch (Exception ex)
            {
                string message = "alert('" + ex.Message + "')";
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "clientScript", message, true);
            }
        }

        protected void btApprove_Click(object sender, EventArgs e)
        {
            try
            {
                if (DangKhuyenMai_GridView.SelectedIndex < 0)
                    return;
                int id = int.Parse(DangKhuyenMai_GridView.Rows[DangKhuyenMai_GridView.SelectedIndex].Cells[1].Text);
                PRODUCT product = ProductBUS.GetProduct(id);
                if (product.STATUS == 0)
                {
                    ProductBUS.ApproveProduct(id);
                    SendMail(product);
                    ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "clientScript", "alert('Qúa Trình Thực Hiện Thành Công, Tin Khuyến Mãi Đã Được Duyệt !!!!')", true);
                    GridViewDataBind();
                }
                else
                {
                    ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "clientScript", "alert(' Tin Khuyến Mãi Đã Được Duyệt rồi !!!!')", true);
                }
            }
            catch (Exception ex)
            {
                string message = "alert('" + ex.Message + "')";
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "clientScript", message, true);
            }
        }


        public void SendMail(PRODUCT product)
        {           
            List<REGISTER_MAIL> listMail = Register_mailBUS.GetAllRegister_mail();
            if (listMail.Count == 0)
                return;
           MailMessage msg = new MailMessage();
            msg.IsBodyHtml = true;
            msg.From = new MailAddress("muare@yahoo.com", "Admin muare.vn");
            for (int i = 0; i < listMail.Count; ++i)
            {
                msg.To.Add(new MailAddress(listMail[i].EMAIL.Trim()));
            }
            msg.Subject = "Sắp Khuyến mãi từ Muare.com : " +product.Name_Product;
            msg.Body = "Sản phẩm sắp khuyễn mại tại Muare.com : " +product.Name_Product + "  \n  Thời Gian khuyến mãi từ  " + product.TIME_START.Value.ToShortDateString() + "  Đến  "
               + product.TIME_STOP.Value.ToShortDateString() + "\n  chi tiết thông tin sản phẩm và khuyến mãi vui long truy cập vào website Muare.com";
            // Send the message
           SmtpClient client = new SmtpClient("smtp.mail.yahoo.com.vn", 25);
            client.Credentials = new NetworkCredential("muare", "admin08");
            client.EnableSsl = false;
            client.Send(msg);
        }

    }
}
